/*
 * @(#)BitmapManager.java	 2011-11-10
 *
 * Copyright 2004-2011 WXXR Network Technology Co. Ltd. 
 * All rights reserved.
 * 
 * WXXR PROPRIETARY/CONFIDENTIAL.
 */

package com.ykdl.app.Utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import net.bither.util.NativeUtil;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.util.Base64;


public class BitmapManager {
	/**
	 * 从网上获得图片
	 * 
	 * @param url
	 * @return Bitmap bitmap
	 */
	public static Bitmap getBitmap(String url) {
		InputStream is = null;
		if (url != null) {
			is = getNetInputStream(url);
		}

		Bitmap bitmap = BitmapFactory.decodeStream(is);
		try {
			if (is != null) {
				is.close();
			}

		} catch (IOException e) {
			return null;
		}
		return bitmap;

	}

	private static InputStream getNetInputStream(String urlStr) {

		try {
			URL url = new URL(urlStr);
			URLConnection conn = url.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			return is;
		} catch (Exception e) {
		}
		return null;
	}

	public static Bitmap decreaseBitmap(String path) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inSampleSize = 6;
		Bitmap resizeBmp = BitmapFactory.decodeFile(path, opts);
		int w = resizeBmp.getWidth();
		int h = resizeBmp.getHeight();
		Matrix matrix = new Matrix();
		if (w > h) {
			matrix.postRotate(90, (float) 360 / 2, (float) 480 / 2);
			float scaleW = (float) 360 / h;
			float scaleH = (float) 480 / w;
			if (scaleW > 1 && scaleH > 1) {
				matrix.postScale(1, 1);
			} else {
				if (scaleW > scaleH) {
					matrix.postScale(scaleW, scaleW);
				} else {
					matrix.postScale(scaleH, scaleH);
				}
			}
		} else {
			float scaleW = (float) 360 / w;
			float scaleH = (float) 480 / h;
			if (scaleW > 1 && scaleH > 1) {
				matrix.postScale(1, 1);
			} else {
				if (scaleW > scaleH) {
					matrix.postScale(scaleW, scaleW);
				} else {
					matrix.postScale(scaleH, scaleH);
				}
			}
		}
		Bitmap newBitmap = Bitmap.createBitmap(resizeBmp, 0, 0, w, h, matrix,
				true);
		if (resizeBmp.isRecycled() == false) {
			resizeBmp.recycle();
			System.gc();
		}
		return newBitmap;
	}

	public static void saveBitmap(String filename,Bitmap bm ){  
        //String filename = "/mnt/sdcard/a.png";  
        if (null == bm || bm.getWidth() == 0 || bm.getHeight() == 0){  
            return;  
        }      
        File temp = new File(filename);  
        FileOutputStream fout = null;  
        try{  
            temp.createNewFile();  
            fout = new FileOutputStream(temp);  
        }catch (IOException e){  
            e.printStackTrace();  
        }  
        //修改图片压缩算法
        	NativeUtil.compressBitmap(bm, 200,
        			temp.getAbsolutePath(), false);
//        bm.compress(Bitmap.CompressFormat.PNG, 50, fout);  
//        int degree = readPictureDegree(filename);
//		bm = rotateBitmap(bm,degree) ;
        
        try {  
            fout.flush();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        try {  
            fout.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        if (!bm.isRecycled()){  
            bm.recycle();  
        }  
    }  
	
	/**
	 * 获取图片的完整代码，解决图片旋转问题
	 * @param filePath
	 * @return
	 */
	public static Bitmap getSmallBitmap(String filePath) {
    	
		Bitmap bm = getZoomBitmap(filePath);
		int degree = readPictureDegree(filePath);
		bm = rotateBitmap(bm,degree) ;
		ByteArrayOutputStream baos = null ;
		try{
			baos = new ByteArrayOutputStream();
			if (bm!=null) {
				
				bm.compress(Bitmap.CompressFormat.JPEG, 50, baos);
			}
			
		}finally{
			try {
				if(baos != null)
					baos.close() ;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bm ;

	}

	private static Bitmap getZoomBitmap(String filePath) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, 480, 800);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		
		Bitmap bm = BitmapFactory.decodeFile(filePath, options);
		if(bm == null){
			return  null;
		}
		return bm;
	}
	
	private static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			// Calculate ratios of height and width to requested height and
			// width
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);

			// Choose the smallest ratio as inSampleSize value, this will
			// guarantee
			// a final image with both dimensions larger than or equal to the
			// requested height and width.
			inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
		}

		return inSampleSize;
	}
	/**
	 * 读取图片属性：旋转的角度
	 * @param path 图片绝对路径
	 * @return degree旋转的角度
	 */
    public static  int readPictureDegree(String path) {
        int degree  = 0;
        try {
                ExifInterface exifInterface = new ExifInterface(path);
                int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                        degree = 90;
                        break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                        degree = 180;
                        break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                        degree = 270;
                        break;
                }
        } catch (IOException e) {
                e.printStackTrace();
        }
        return degree;
    }
    private static Bitmap rotateBitmap(Bitmap bitmap, int rotate){
		if(bitmap == null)
			return null ;
		
		int w = bitmap.getWidth();
		int h = bitmap.getHeight();

		// Setting post rotate to 90
		Matrix mtx = new Matrix();
		mtx.postRotate(rotate);
		return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
	}
    
    @SuppressLint("NewApi")
	public static String bitmapToString(String filePath) {

		Bitmap bm = getSmallBitmap(filePath);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
		byte[] b = baos.toByteArray();

		return Base64.encodeToString(b, Base64.DEFAULT);

	}
}
